import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        list: JSON.parse(localStorage.getItem('todo')) || [],
        type: "all"
    },
    mutations: {
        addTodo: (state, name) => { // 添加元素
            let id = state.list.length === 0 ? 100 : state.list[state.list.length - 1].id + 1;
            if (name.length === 0) return alert('输入的内容不能为空')
            state.list.push({
                id,
                name,
                isDone: false
            })
        },
        deleteTodo: (state, id) => { //删除元素
            let index = state.list.findIndex((item) => item.id === id)
            console.log(index);
            state.list.splice(index, 1)
        },
        typeTodo: (state, isAll) => { // 分类显示
            state.type = isAll
        },
         clearTodo: async (state) => { // 清除已完成
            state.list = await state.list.filter(obj => obj.isDone === false)
            localStorage.setItem('todo', JSON.stringify(state.list))
        }
    },
    getters: {
        getSum(state) { // 统计数量
            return state.list.length
        },
        showType: (state) => {
            if (state.type === "yes") {
                return state.list.filter((obj) => obj.isDone === true);
            } else if (state.type === "no") {
                return state.list.filter((obj) => obj.isDone === false);
            } else {
                return state.list;
            }
        }
    }
})